import scrapy
import requests
from bid.items import BidItem
from bid.tools import *


class HainanSpider(scrapy.Spider):
    name = 'hainan'
    allowed_domains = ['zw.hainan.gov.cn']
    start_urls = ['https://zw.hainan.gov.cn/']
    t_lis = [
        ['http://zw.hainan.gov.cn/ggzy/ggzy/jgzbgg/index%s.jhtml', '工程建设-招标公告','1'],
        ['http://zw.hainan.gov.cn/ggzy/ggzy/jgzbgs/index%s.jhtml', '工程建设-中标公示','3'],
        ['http://zw.hainan.gov.cn/ggzy/ggzy/jsqtgg/index%s.jhtml', '工程建设-其他公告','2'],
        ['http://zw.hainan.gov.cn/ggzy/ggzy/cggg/index%s.jhtml', '政府采购-采购公告','1'],
        ['http://zw.hainan.gov.cn/ggzy/ggzy/cgzbgg/index%s.jhtml', '政府采购-中标公告','3'],
        ['http://zw.hainan.gov.cn/ggzy/ggzy/zfcgqtgg/index%s.jhtml', '政府采购-其他公告','2'],
    ]
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg = []
    def start_requests(self):
        for lis in self.t_lis:
            print(lis[1],'开始')
            for page in range(1, 9999):
                if page == 1:
                    res = requests.get(lis[0] % '', headers=self.headers)
                else:
                    res = requests.get(lis[0] % f'_{page}', headers=self.headers)
                res.encoding = 'utf-8'
                ls = re.findall('<td align="left"><a href="(.*?)" title="(.*?)".*?<td align="center">(.*?)<', res.text, re.S)
                last_page = re.findall('条记录 \d+/(\d+)页', res.text, re.S)[0]
                if page > int(last_page):
                    break
                for l in ls:
                    item = {}
                    item['link'] = l[0]
                    item['title'] = l[1]
                    item['time'] = l[2]
                    item['classification'] = '海南-'+lis[1]
                    item['typ'] = lis[-1]
                    if redis_dupefilter(item) or item['time'].startswith('2021'):
                        self.msg.append(lis)
                        break
                    yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
                if lis in self.msg:
                    print(lis[1],'完成')
                    break
                time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="newsCon"]')
        item = get_field(dict(item))
        yield item
